package com.malred;

/**
 * @author malguy-wang sir
 * @create ---
 */
public class myLinkList<E> {
    transient int size = 0;//当前链表的大小
    //头尾节点
    transient Node last = null;
    transient Node first = null;
    public E getData(int index) {
        return get(index).data;
    }
    private Node<E> get(int index) {
        //如果index小于size除2,从头开始查
        if (index > size) return null;
        if (index < (size >> 1)) {
            Node<E> x = first;//从头
            for (int i = 0; i < index; i++) {
                x = x.next;//获取下一个,直到index
            }
            return x;
        } else {
            //如果index在后半段,就从后开始查
            Node<E> x = last;
            for (int i = size - 1; i > index; i--) {
                x = x.pre;
            }
            return x;
        }
    }
    public void remove(int index){
        //找到删除的节点,然后把它的前后节点连起来
        Node tar = get(index);
        if(tar == null) return;
        Node pre = tar.pre;
        Node next = tar.next;
        if(pre==null) {
            //如果是头节点
            first = next;
        }else {
            pre.next = next;
            tar.pre = null;
        }
        if(next==null){
            last = pre;
        }else {
            next.pre = pre;
            tar.next = null;
        }
        tar.data=null;
        size--;
    }
    public void show(){
        System.out.print("[");
        for (int i = 0; i < size; i++) {
            System.out.print(get(i)+" ");
        }
        System.out.println("]");
    }
    public void add(E e) {
        //获取当前尾节点
        Node<E> l = last;
        Node<E> newNode = new Node<E>(l, e, null);
        last = newNode;//指定新的尾节点
        if (l == null) {
            first = newNode;//如果当前没有尾节点,表示这是头节点
            size++;
        } else {
            l.next = newNode;//如果有尾节点,则尾节点的下一个指向新增节点,新增节点变成尾节点
            newNode.pre = l;
            size++;
        }
    }
    class Node<E> {
        E data;//保存的数据
        Node<E> next;//下一个节点
        Node<E> pre;//上一个节点
        public Node(Node<E> pre, E data, Node<E> next) {
            this.data = data;
            this.next = next;
            this.pre = pre;
        }

        @Override
        public String toString() {
            return "Node = "+data;
        }
    }
}

